package eu.kuresson.tower.web;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeAction;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;

import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.authorization.Action;

//show for anonymous users only
@AuthorizeAction(action = Action.RENDER, roles = "is_anonymous")
public final class LoginPanel extends Panel {
	private HomePage parent;
	
	public LoginPanel(String id, HomePage parent) {
		super(id);
		this.parent = parent;
		add(new LoginForm("loginform"));
	}

	class LoginForm extends Form {

		private String user;
		private String password;

		public LoginForm(String id) {
			super(id);
			setDefaultModel(new CompoundPropertyModel(this));
			add(new RequiredTextField("user"));
			add(new PasswordTextField("password"));
			add(new FeedbackPanel("feedback"));
			add(new AjaxLink<Void>("registerButton") {
				@Override
				public void onClick(AjaxRequestTarget target) {
					 setResponsePage(RegisterPage.class);
				}
			});
		}

		@Override
		protected void onSubmit() {
			SpringWicketWebSession session = SpringWicketWebSession
					.getSpringWicketWebSession();
			if (session.signIn(user, password)) {
				// redirect here
				// error("Login success!");
				// login user

				// goto home page
				setResponsePage(getApplication().getHomePage());
			} else {
				error("Wrong Username or Password!");
			}
		}

	}
}